package com.bsy.network.adapter

import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import java.lang.reflect.Type


class LongDefaultAdapter : JsonSerializer<Long>, JsonDeserializer<Long> {

    override fun serialize(
        src: Long?,
        typeOfSrc: Type?,
        context: JsonSerializationContext?
    ): JsonElement {
        return JsonPrimitive(src);
    }

    override fun deserialize(
        json: JsonElement,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): Long {
        try {
            if (json.asString.equals("") || json.asString.equals("null")  || json.isJsonNull) {
                return 0
            }

            json.asString.toLongOrNull()?.let {
                return it
            }

        } catch (ignore: Exception) {
            return 0
        }
        return try {
            json.asLong
        } catch (e: NumberFormatException) {
            return 0
        }
    }
}